package com.hushui.mall.coupon.configuration;

import com.hushui.mall.coupon.service.SeckillSessionService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架
 */

@Slf4j
@Component
@EnableAsync    //开启异步任务
@EnableScheduling   //开启定时任务
public class SeckillSkuConfig {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    SeckillSessionService seckillSessionService;

    private final String UPLOAD_LOCK = "seckill:upload:lock";

    /**
     * 异步上架最近三天的商品（加入redis缓存）
     */
    @Async
    @Scheduled(cron = "0 * * * * ? ")
    public void uploadSeckillSkuLatest3Days(){
        //分布式锁，防止多个服务启动重复执行
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            log.info("执行同步任务..");
            // 缓存最近三天的活动
            seckillSessionService.uploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }
    }
}
